//
//  PSFilterWhisterFirstHandMove.m
//  PrefCore
//
//  Created by Sergey on 6/20/14.
//  Copyright (c) 2014 Play-on-smart. All rights reserved.
//

#import "PSFilter.h"

// We should get here only if a player is whister or passer during tricking game
PSHandHash PSFilterWhisterFirstHandMove(
    PSHandHash candidates
,   PSHandHash playerCards
,   PSHandHash declarerCards
) {
    PSHandHash res = candidates;
    for (int i = 0 ; i != PS_CARD_SUIT_RISING_LEN ; i++) {
        PSCardSuit suit = PSCardSuitRising[i];
        if (PSHandKeepSuit(candidates, suit) != 0) {
            PSCardRankSet cards = PSHandGetSuit(declarerCards, suit);
            PSCardIndex cardsLength = PSCardSetSize(cards);
            
            PSCardRankSet whisterCards = PSHandGetSuit(playerCards, suit);
            PSCardIndex whisterCardsLength = PSCardSetSize(whisterCards);
            
            // second+ king situation (without queen)
            BOOL ace = PSCardSetContainsCard(cards, kMaskAce);
            BOOL secondKing = ace
                           && cardsLength > 1
                           && PSCardSetContainsCard(whisterCards, kMaskKing)
                           && !PSCardSetContainsCard(whisterCards, kMaskQueen)
                           && whisterCardsLength > 1
                           && whisterCardsLength < 4;
            
            // third+ queen situation
            BOOL king = PSCardSetContainsCard(cards, kMaskKing);
            
            BOOL thirdQueen = PSCardSetContainsCard(whisterCards, kMaskQueen)
                           && ((ace && king && cardsLength > 2 && whisterCardsLength > 2)
                            || (ace && !king && cardsLength > 1 && whisterCardsLength > 1)
                            || (!ace && king && cardsLength > 1 && whisterCardsLength > 1)
                           );
            
            // fourth jack situation
            BOOL queen = PSCardSetContainsCard(cards, kMaskQueen);
            
            BOOL fourthJack = ace && king && queen
                           && cardsLength > 3
                           && whisterCardsLength > 3
                           && PSCardSetContainsCard(whisterCards, kMaskJack);
            
            // in one of the below situations remove the entire suit for the candidates
            if (secondKing || thirdQueen || fourthJack) {
                res = PSHandRemoveSuit(res, suit);
            }
        }
    }
    return res != 0 ? res : candidates;
}
